import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { FormattedMessage } from 'react-intl';
import { stripesConnect } from '@folio/stripes/core';
import get from 'lodash/get';
import { MultiColumnList } from '@folio/stripes/components';
import { StripesConnectedSource } from '@folio/stripes/smart-components';
import SearchForm from '../../components/party-briefing/search-form';
import ExprotExcel from '../../util/ExportExcel';

class DetailsStatistics extends Component {
  static manifest = Object.freeze({

    partyBriefingQuery: { initialValue: '' },
    resultCount: { initialValue: 10 },
    detailsRecords: {
      type: 'okapi',
      path: 'party/data',
      recordsRequired: '%{resultCount}',
      perRequest: 10,
      limitParam: 'limit',
      records: 'partyDataGroup',
      GET: {
        params: {
          query: '%{partyBriefingQuery}'
        }
      }
    },
    activityClassificationHttpInvoke: {
      type: 'okapi',
      accumulate: true,
      path: () => 'party/property'
    },
    activityClassificationRequest: {
      type: 'okapi',
      accumulate: true,
      path: () => 'party/property'
    }
  });

  static propTypes = {
    okapi: PropTypes.object,
    stripes: PropTypes.shape({
      logger: PropTypes.object
    }).isRequired,
    resources: PropTypes.object,
    mutator: PropTypes.shape({

      partyBriefingQuery: PropTypes.string,
      activityClassificationHttpInvoke: PropTypes.shape({
        PUT: PropTypes.func.isRequired,
        POST: PropTypes.func.isRequired,
        GET: PropTypes.func.isRequired,
        DELETE: PropTypes.func.isRequired
      }),
      activityClassificationRequest: PropTypes.shape({
        GET: PropTypes.func.isRequired
      })
    }).isRequired,
    dictionary: PropTypes.object
  };

  constructor(props) {
    super(props);
    this.logger = props.stripes.logger;
    this.log = this.logger.log.bind(this.logger);
    this.state = {
      searchFlag: true,
      searchForm: {},
      ascriptionList: []
    };
  }

  componentDidMount() {
    this.source = new StripesConnectedSource(this.props, this.logger);
    this.getClassificationList();
  }

  componentDidUpdate() {
    this.source.update(this.props, 'detailsRecords');
  }

  componentWillUnmount() {
    const { mutator, resources } = this.props;

    mutator.partyBriefingQuery.replace('');
  }

  search = ({ requestPreferences, creds, ...formData }) => {
    const { mutator } = this.props;
    let query = '';
    if (formData.propertyName) {
      query += ` and propertyName = ${formData.propertyName}* `;
    }

    if (formData.name) {
      query += ` and name = ${formData.name}* `;
    }
    if (!!formData.partyEndDate && !formData.partyStartDate) {
      query += ` and partyEndDate >= "${formData.partyEndDate} 00:00:00"
                  and partyEndDate <= "${formData.partyEndDate} 23:59:59" `;
    }
    if (!!formData.partyStartDate && !formData.partyEndDate) {
      query += ` and partyStartDate >= "${formData.partyStartDate} 00:00:00"
                     partyStartDate <= "${formData.partyStartDate} 23:59:59" `;
    }
    if (!!formData.partyStartDate && !!formData.partyEndDate) {
      query += ` and partyStartDate >= "${formData.partyStartDate} 00:00:00"
                    and partyEndDate <= "${formData.partyEndDate} 23:59:59" `;
    }
    if (query) {
      query = `(${query.substr(4, query.length)})`;
    }

    mutator.partyBriefingQuery.replace(query);
    if (this.source && this.state.searchFlag) {
      this.source.update(this.props, 'detailsRecords');
      this.setState(
        {
          searchForm: formData,
          searchFlag: false
        },
        () => {
          setTimeout(() => {
            this.setState({
              searchFlag: true
            });
          }, 500);
        }
      );
    }
    //    mutator.query.replace(JSON.stringify(formData));
    //    if (this.source) {
    //      this.source.update(this.props, 'detailsRecords');
    //      this.setState({
    //        searchForm: formData
    //      });
    //    }
  };

  moreData = () => {
    if (this.source) {
      this.source.fetchMore(10);
    }
  };

  exportExcel = () => {
    const params = this.state.searchForm;
    const p = params;
    const okapi = this.props.okapi;
    const path = okapi.url + '/party/data/export_excel';
    const requestParams = ExprotExcel.objToParam(p);
    const fileName = '活动详情统计';
    const type = 'GET';
    ExprotExcel.exprot(
      path,
      requestParams,
      type,
      fileName,
      okapi.token,
      okapi.tenant
    );
  };

  getClassificationList = () => {
    const val = JSON.stringify({ ascriptionId: '0' });
    const {intl} = this.props
    const params = {
      params: {
        query: '( isDel = 0 and parentId <> 0 )'
      }
    };
    const { GET } = this.props.mutator.activityClassificationRequest;
    GET(params).then(response => {
      const list = response.propertyGroup;

      if (list) {
        const ascriptionList = [
          {
            value: '',
            label: intl.formatMessage({id:"ui-party.other.please.select.activity.type"})  ,
            id: ''
          }
        ];

        list.forEach(value => {
          const tmp = {
            value: value.name,
            label: value.name,
            id: value.id
          };

          ascriptionList.push(tmp);
        });
        this.setState({
          ascriptionList
        });
      }
    });
  };

  render() {
    const { resources } = this.props;
    if (this.source) {
      this.source.update(this.props, 'detailsRecords');
    }

    const able = document.getElementsByClassName('mclScrollable---IM56u');
    if (able && able[0]) {
      able[0].style.width = '102%';
    }

    const totalCount = this.source ? this.source.totalCount() : 0;
    const dataList = get(resources, 'detailsRecords.records', []);
    const formatter = {
      serialNumber: (
        <FormattedMessage id="ui-party.loans.columns.serialNumber" />
      ),
      partyName: <FormattedMessage id="ui-party.loans.columns.party.partyName" />,
      partyStartDate: (
        <FormattedMessage id="ui-party.loans.columns.party.partyStartDate" />
      ),
      reserveAmount: (
        <FormattedMessage id="ui-party.loans.columns.party.briefing.report.reserveAmount" />
      ),
      attendAmount: (
        <FormattedMessage id="ui-party.loans.columns.party.briefing.report.attendAmount" />
      ),
      viewAmount: (
        <FormattedMessage id="ui-party.loans.columns.party.briefing.report.viewAmount" />
      ),
      attendPercent: (
        <FormattedMessage id="ui-party.loans.columns.party.briefing.report.attendAmount" />
      ),
      leavePercent: (
        <FormattedMessage id="ui-party.loans.columns.party.briefing.report.leavePercent" />
      ),
      absencePercent: (
        <FormattedMessage id="ui-party.loans.columns.party.briefing.report.absencePercent" />
      )
    };
    return (
      <div>
        <SearchForm
          onSubmit={this.search}
          exportExcel={() => {
            this.exportExcel();
          }}
          ascriptionList={this.state.ascriptionList}
        />
        <MultiColumnList
          interactive={false}
          maxHeight={500}
          isEmptyMessage={<FormattedMessage id="ui-party.empty.list" />} // 空数据提示
          totalCount={totalCount}
          virtualize
          contentData={dataList}
          onNeedMoreData={this.moreData}
          columnMapping={formatter}
          columnWidths={{
            serialNumber: '5%',
            partyName: '15%',
            partyStartDate: '15%',
            reserveAmount: '10%',
            attendAmount: '10%',
            viewAmount: '10%',
            attendPercent: '10%',
            leavePercent: '10%',
            absencePercent: '10%'
          }}
          visibleColumns={[
            'serialNumber',
            'partyName',
            'partyStartDate',
            'reserveAmount',
            'attendAmount',
            'viewAmount',
            'attendPercent',
            'leavePercent',
            'absencePercent'
          ]}
          formatter={{
            serialNumber: item => [<span>{item.rowIndex + 1}</span>],
            partyName: item => [
              <div
                title={item.partyName}
                style={{
                  whiteSpace: 'nowrap',
                  overflow: 'hidden',
                  textOverflow: 'ellipsis'
                }}
              >
                {item.partyName}
              </div>
            ]
          }}
        />
      </div>
    );
  }
}

export default stripesConnect(DetailsStatistics);
